package com.jike.jkgame;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

import com.jike.jkgame.data.UserStatus;
import com.jike.jkgame.exception.EncodingException;
import com.jike.jkgame.exception.NetworkErrorException;
import com.jike.jkgame.network.MessageFactory;
import com.jike.jkgame.network.NetworkUtilis;
import com.jike.jkgame.network.ServerConfig;

public class UserInfoActivity extends FragmentActivity implements
		OnClickListener {

	private TabHost mTabHost;
	private ImageView mBackIv;
	private View mUserStatusView;

	private TextView mEnergyTimerTv;
	private TextView mEnergyTimerAllTv;
	private TextView mVigourTimerTv;
	private TextView mVigourTimerAllTv;
	private TextView mNoWarTimerTv;

	private TextView mGeneralsCntTv;
	private TextView mArmyAttackTv;
	private TextView mArmyDefenseTv;
	private TextView mBaseAttackTv;
	private TextView mBaseDefenseTv;

	private TextView mExperienceAddTv;
	private TextView mMoneyAddTv;
	private TextView mEnergyRecoverTv;
	private TextView mVigourRecoverTv;

	private TextView mAttackCntTv;
	private TextView mAttackWinTv;
	private TextView mAttackGetTv;
	private TextView mDefenseCntTv;
	private TextView mDefenseWinTv;
	private TextView mDefenseGetTv;
	
	private Handler mHandler = new Handler(new Callback() {
		
		@Override
		public boolean handleMessage(Message msg) {
			String name = (String) msg.obj;
			
			if (name.equals("Energy")) {
				updateEnergyTimer(msg.arg1, (int) (UserStatus.get().getEnergy().getTotalMillisUntillFull()/1000));
			} else {
				updateVigourTimer(msg.arg1, (int) (UserStatus.get().getVigour().getTotalMillisUntillFull()/1000));
			}
			return false;
		}
		
	});
	
	private void updateEnergyTimer(int remian, int totalRemain) {
		mEnergyTimerTv.setText(Utilis.fromatTime(remian));
		mEnergyTimerAllTv.setText(Utilis.fromatTime(totalRemain));
	}
	
	private void updateVigourTimer(int remian, int totalRemain) {
		mVigourTimerTv.setText(Utilis.fromatTime(remian));
		mVigourTimerAllTv.setText(Utilis.fromatTime(totalRemain));
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.userinfo_layout);
		mUserStatusView = findViewById(R.id.user_status);
		
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup();

		mTabHost.addTab(mTabHost.newTabSpec("basic").setIndicator("基础")
				.setContent(R.id.info_basic));
		mTabHost.addTab(mTabHost.newTabSpec("fight").setIndicator("战斗")
				.setContent(R.id.info_fight));
		
		mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
			
			@Override
			public void onTabChanged(String tabId) {
				if (tabId.equals("basic")) {
					getBasicInfo();
				} else {
					getBattleInfo();
				}
			}
		});

		mBackIv = (ImageView) findViewById(R.id.iv_back);
		
		View v = findViewById(R.id.info_basic);
		mEnergyTimerTv = (TextView) v.findViewById(R.id.tv_energy_timer);
		mEnergyTimerAllTv = (TextView) v.findViewById(R.id.tv_all_energy_timer);
		mVigourTimerTv = (TextView) v.findViewById(R.id.tv_vigour_timer);
		mVigourTimerAllTv = (TextView) v.findViewById(R.id.tv_all_vigour_timer);
		mNoWarTimerTv = (TextView) v.findViewById(R.id.tv_nowar_timer);

		mGeneralsCntTv = (TextView) v.findViewById(R.id.tv_generalcnt);
		mArmyAttackTv = (TextView) v.findViewById(R.id.tv_all_attack);
		mArmyDefenseTv = (TextView) v.findViewById(R.id.tv_all_defense);
		mBaseAttackTv = (TextView) v.findViewById(R.id.tv_attack);
		mBaseDefenseTv = (TextView) v.findViewById(R.id.tv_defense);

		mExperienceAddTv = (TextView) v.findViewById(R.id.tv_add_exp);
		mMoneyAddTv = (TextView) v.findViewById(R.id.tv_add_money);
		mEnergyRecoverTv = (TextView) v.findViewById(R.id.tv_recover_energy_time);
		mVigourRecoverTv = (TextView) v.findViewById(R.id.tv_recover_vigour_time);
		
		v = findViewById(R.id.info_fight);
		mAttackCntTv = (TextView) v.findViewById(R.id.tv_att_cnt);
		mAttackWinTv = (TextView) v.findViewById(R.id.tv_att_win_percent);
		mAttackGetTv = (TextView) v.findViewById(R.id.tv_att_get);
		mDefenseCntTv = (TextView) v.findViewById(R.id.tv_def_count);
		mDefenseWinTv = (TextView) v.findViewById(R.id.tv_def_succeed_percent);
		mDefenseGetTv = (TextView) v.findViewById(R.id.tv_def_get);

		mBackIv.setOnClickListener(this);

		getBasicInfo();
	}

	@Override
	protected void onResumeFragments() {
		super.onResumeFragments();
		mUserStatusView.setClickable(false);
		UserStatusViewManager.get().bindView(mUserStatusView);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		default:
			break;
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		UserStatus.get().getEnergy().restoreTargetHandler();
		UserStatus.get().getVigour().restoreTargetHandler();
	}

	@Override
	protected void onResume() {
		UserStatus.get().getEnergy().pushTargetHandler(mHandler);
		UserStatus.get().getVigour().pushTargetHandler(mHandler);
		super.onResume();
	}

	private void getBasicInfo() {
		GetBasicInfoTask task = new GetBasicInfoTask();
		task.execute(null);
	}
	
	private void getBattleInfo() {
		GetBattleInfoTask task = new GetBattleInfoTask();
		task.execute(null);
	}

	class GetBasicInfoTask extends
			AsyncTask<Object, Integer, BasicInfoResultData> {

		@Override
		protected BasicInfoResultData doInBackground(Object... params) {

			JSONObject req = MessageFactory.createGetUserBasicInfoReqMessage();

			try {
				String response = NetworkUtilis.getHttpString(ServerConfig
						.get().getGameServer(), req);

				JSONObject json = new JSONObject(response);
				BasicInfoResultData result = new BasicInfoResultData();
				result.opcode = json.optInt("opcode", -1);
				if (result.opcode != 0) {
					return result;
				}

				result.team_size = json.optInt("team_size");
				result.army_att_max = json.optInt("army_att_max");
				result.army_att_min = json.optInt("army_att_min");
				result.army_def_max = json.optInt("army_def_max");
				result.army_def_min = json.optInt("army_def_min");
				result.base_att = json.optInt("base_att");
				result.base_def = json.optInt("base_def");
				result.exp_add = json.optInt("exp_add");
				result.money_add = json.optInt("money_add");
				result.energy_recover = json.optInt("energy_recover");
				result.vigour_recover = json.optInt("vigour_recover");

				return result;

			} catch (NetworkErrorException e) {
				e.printStackTrace();
			} catch (EncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(BasicInfoResultData result) {
			super.onPostExecute(result);
			bindBasicInfo(result);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

	}

	class GetBattleInfoTask extends
			AsyncTask<Object, Integer, BattleInfoResultData> {

		@Override
		protected BattleInfoResultData doInBackground(Object... params) {
			JSONObject req = MessageFactory.createGetUserBattleInfoReqMessage();

			BattleInfoResultData result = null;
			try {
				String response = NetworkUtilis.getHttpString(ServerConfig
						.get().getGameServer(), req);
				JSONObject json = new JSONObject(response);
				result = new BattleInfoResultData();
				result.opcode = json.optInt("opcode", -1);
				if (result.opcode == 0) {
					result.att = json.optInt("att");
					result.att_win = json.optInt("att_win");
					result.att_money = json.optInt("att_money");
					result.att_item = json.optInt("att_item");
					result.def = json.optInt("def");
					result.def_money = json.optInt("def_money");
				}

				return result;
			} catch (NetworkErrorException e) {
				e.printStackTrace();
			} catch (EncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(BattleInfoResultData result) {
			super.onPostExecute(result);
			bindBattleInfo(result);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		
		

	}

	private void bindBasicInfo(BasicInfoResultData data) {
		if (data == null || data.opcode != 0) {
			return;
		}
		mGeneralsCntTv.setText(String.valueOf(data.team_size));
		mArmyAttackTv.setText(String.format("%d~%d", data.army_att_min,
				data.army_att_max));
		mArmyDefenseTv.setText(String.format("%d~%d", data.army_def_min,
				data.army_def_max));
		mBaseAttackTv.setText(String.valueOf(data.base_att));
		mBaseDefenseTv.setText(String.valueOf(data.base_def));
		mExperienceAddTv.setText(String.format("%d%%", data.exp_add));
		mMoneyAddTv.setText(String.format("%d%%", data.money_add));
		mEnergyRecoverTv.setText(String.format(Utilis.getResString(R.string.seconds_format), data.energy_recover));
		mVigourRecoverTv.setText(String.format(Utilis.getResString(R.string.seconds_format), data.vigour_recover));
	}

	private void bindBattleInfo(BattleInfoResultData data) {
		if (data == null || data.opcode != 0) {
			return;
		}

		mAttackCntTv.setText(String.format(
				Utilis.getResString(R.string.attack_count_format),
				data.att, data.att_win));
		mAttackWinTv.setText(String.format(
				Utilis.getResString(R.string.attack_win_per_format), 100f
						* data.att_win / data.att));
		mAttackGetTv.setText(String.format(
				Utilis.getResString(R.string.attack_win_get_format),
				data.att_money, data.att_item));
		mDefenseCntTv.setText(String.format(
				Utilis.getResString(R.string.defense_count_format),
				data.def, data.def_win));
		mDefenseWinTv.setText(String.format(
				Utilis.getResString(R.string.defense_win_per_format), 100f
						* data.def_win / data.def));
		mDefenseGetTv.setText(String.format(
				Utilis.getResString(R.string.defense_win_get_format),
				data.def_money));
	}

	private static class BasicInfoResultData {
		public int opcode;
		public int team_size;
		public int army_att_max;
		public int army_att_min;
		public int army_def_max;
		public int army_def_min;
		public int base_att;
		public int base_def;
		public int exp_add;
		public int money_add;
		public int energy_recover;
		public int vigour_recover;
	}

	private static class BattleInfoResultData {
		public int opcode;
		public int att;
		public int att_win;
		public int att_money;
		public int att_item;
		public int def;
		public int def_win;
		public int def_money;
	}

}
